//
//  timer_interrupt.c
//  electronic_clock
//
//  Created by fukai on 2018/10.
//  Copyright © 2018年 赛博智能车实验室. All rights reserved.
//

#include "stm32f10x.h"	//ST公司v3.5版本使用的库函数头文件
#include "timer_interrupt.h"
#include "key.h"
#include "led.h"
#include "clock_os.h"
#include "beep.h"


//定时器2中断初始化函数
void Tim2IntInit(unsigned int arr,unsigned int psc)
{
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;	//定义定时器初始化参数结构体
	NVIC_InitTypeDef NVIC_InitStructure;			//定义嵌套向量中断结构体
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //时钟使能
	
	TIM_TimeBaseStructure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值	 计数到5000为500ms
	TIM_TimeBaseStructure.TIM_Prescaler =psc; //设置用来作为TIMx时钟频率除数的预分频值(分频系数) 当psc为7200时，72M/7200=10Khz的计数频率（即10k次为1s）
	TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //TIM向上计数模式
	TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位
	
	TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);	//使能tim2的更新中断
	
	NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;  //TIM2中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  //先占优先级0级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;  //从优先级3级
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
	NVIC_Init(&NVIC_InitStructure);  //根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器
	
	TIM_Cmd(TIM2, ENABLE);  //使能TIMx外设
}

//TIM2中断服务函数
void TIM2_IRQHandler(void)   
{
	if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) //检查指定的TIM中断发生与否:TIM 中断源 
	{
		TIM_ClearITPendingBit(TIM2, TIM_IT_Update);  //清除TIMx的中断待处理位:TIM 中断源 
		
		//当处于时钟设置、闹钟、计时器界面时才启动长按功能
		if(ClockDisplay.ClockDisplayStatus == CLOCK_SET || ClockDisplay.ClockDisplayStatus == ALARM_SET || ClockDisplay.ClockDisplayStatus == TIMER_SET)
		{
			KeyContinuousCheck();//按键长按检测
		}
		ClockWork(&Clock,1000);
		StopWatchWork(&Clock,10);
		AlarmWork(&Clock,1000,10);
		TimerWork(&Clock,1000,10);
		
		if(Clock.AlarmClockWorkStatus == ALARM_WORKING || Clock.TimerWorkStatus == TIMER_ALARM)//闹钟响铃时打开LED灯
		{
			FlowLampOn(30);
			BeepSing(90);
		}
		else
		{
			FlowLampOff();
			BeepStop();
		}
		
		FlickerShow(300);//闪烁显示标志切换
		
	}
}


